import collections
from .loggers import dev_logger, record_logger

# 定义接收信息的具名元组结构
RecvMsg = collections.namedtuple("RecvMsg", ["id", "data"])

def singleton(cls):
    '''
        单例模式的装饰器
    '''
    instances = {}
    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return get_instance


class MsgQueue:
    '''
        self.deque 是一个双端队列，用于存储接收到的消息
    '''
    def __init__(self, key_symbol, filter_ids = None) -> None:
        # filter_ids 是过滤器id清单
        self.filter_ids = filter_ids
        self.key_symbol = key_symbol
        self.deque = collections.deque(maxlen=200)
    
    def addMsg(self, msg):
        '''
        往deque中增加msg
        '''
        if self.filter_ids is None:
            self.deque.append(msg)
        elif msg.id in self.filter_ids:
            self.deque.append(msg)
        
    def clear(self):
        self.deque.clear()



@singleton
class UnitTestRecvQueue:

    queue_dict = {}

    def __init__(self) -> None:
        pass

    def create_queue(self, key_symbol):
        '''
        创建一个queue,要给key_symbol唯一命名
        '''
        if key_symbol not in self.queue_dict:
            self.queue_dict[key_symbol] = MsgQueue(key_symbol)
        else:
            raise Exception(f'{key_symbol} queue already exists')
        dev_logger.debug(str(self.queue_dict))
        return self.queue_dict[key_symbol]
    
    def get_queue(self, key_symbol):
        '''
        获取一个queue
        '''
        if key_symbol not in self.queue_dict:
            raise Exception('queue not exists')
        return self.queue_dict[key_symbol]
    
    def del_queue(self, key_symbol):
        '''
        删除指定的queue
        '''
        self.queue_dict.pop(key_symbol)
    
    def append_msg_to_queues(self, msg):
        for key in self.queue_dict:
            self.queue_dict[key].addMsg(msg)



# 创建一个单例的接收队列清单，存储了多个队列
unitTestRecvQueues =  UnitTestRecvQueue()



def  executor_pool_exception_callback(worker):
    # 将子线程的异常信息记录到日志中
    dev_logger.debug('子线程add_done_callback回调函数被调用了')
    # 判断一下子线程是否有异常
    worker_exception = worker.exception()
    if worker_exception:
        dev_logger.warning(f"worker return exception:{worker_exception}")
        record_logger.warning(f"worker return exception:{worker_exception}")

def main():
    pass
    # ut = unitTestRecvQueues.create_queue('1234')
    pass
    pass
    
if __name__ == '__main__':
    main()